/*
 *******************************************************************
 *
 * COPYRIGHT (coffee) 2013 - 2014 LTV Co., Ltd  All rights reserved
 *
 * Created  : Mar 9, 2014
 * Change History
 * =================================================================
 * DATE                DEVELOPER        REVISION      DESCRIPTION
 * =================================================================
 * Mar 9, 2014        Steven        1.0           First Created.
 * =================================================================
 *
 *
 *******************************************************************/
/**
 * 
 */
package vn.com.ltv.lo;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import vn.com.ltv.lo.common.Constants;
import vn.com.ltv.lo.common.Decrypter;
import vn.com.ltv.lo.common.DialogUtil;
import vn.com.ltv.lo.common.SessionManager;
import vn.com.ltv.lo.common.Validate;
import vn.com.ltv.lo.daos.UserDAO;
import vn.com.ltv.lo.dtos.UserDTO;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * @author Steven
 *
 */
public class RegisterActivity extends Activity implements View.OnClickListener{
	
	//-----------Define variables---------------
	EditText edtFullName,edtEmail,edtPass;
	CheckBox cbxShowpass;
	Button btnRegister;
	TextView tvLogin;
	LinearLayout lnLogin;
	
	String sEmail,sPassword,sFullName;
	String err = "";
	
	// Session Manager Class
    SessionManager session;
	
	//-----------Request Service---------------
	private HttpClient client = new DefaultHttpClient();		                
    private HttpResponse response;
    private JSONObject json = new JSONObject();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.register);		
		init();
		
		//-----------Actions---------------
		btnRegister.setOnClickListener(this);
		lnLogin.setOnClickListener(this);
		
		cbxShowpass.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if (!cbxShowpass.isChecked()) {
					edtPass.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
				} else {
					edtPass.setInputType(InputType.TYPE_CLASS_TEXT);
				}
			}
		});
	}
	
	private void init(){
		edtFullName = (EditText)findViewById(R.id.register_edtFullName);
		edtEmail = (EditText)findViewById(R.id.register_edtEmail);
		edtPass = (EditText)findViewById(R.id.register_edtPass);
		cbxShowpass = (CheckBox)findViewById(R.id.register_cbxShowpass);
		btnRegister = (Button)findViewById(R.id.register_btnRegister);
		tvLogin = (TextView)findViewById(R.id.register_tvLogin);
		lnLogin = (LinearLayout)findViewById(R.id.register_lnLogin);
		
		session = new SessionManager(RegisterActivity.this); 
		//------set textview underline-------		
		tvLogin.setPaintFlags(tvLogin.getPaintFlags() |   Paint.UNDERLINE_TEXT_FLAG);
		//------set input password field---------
		edtEmail.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_EMAIL_ADDRESS);
		
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		//----------textview login is clicked----------
		case R.id.register_lnLogin:
			intent = new Intent(RegisterActivity.this, LoginActivity.class);
			startActivity(intent);
			break;
		
		//----------button register is clicked----------
		case R.id.register_btnRegister:
			err = "";
			sFullName =  edtFullName.getText().toString().trim();
			sEmail = edtEmail.getText().toString().trim();
			sPassword = edtPass.getText().toString().trim();				
			
			checkData();
							
			if (err.equals("")) {
				if (register()) {
					session.createLoginSession("", sEmail);
					intent = new Intent(RegisterActivity.this, Home.class);
					startActivity(intent);					
				} else {
					DialogUtil.CreateDialog(RegisterActivity.this, Constants.ERR_REGISTER_REQUEST);
					DialogUtil.dialog.show();
				}
								
			} else {
				DialogUtil.CreateDialog(RegisterActivity.this, err);
				DialogUtil.dialog.show();
			}
			break;

		default:
			break;
		}
	}
	
	private boolean checkData(){
		//----------check empty fields--------------
		if (sFullName.equals("")) {
			err = "Full name is empty !";
			return false;
		} else {
			if (sEmail.equals("")) {
				err = "Email is empty !";
				return false;
			}else{
				if (sPassword.equals("")) {
					err = "Password is empty !";
					return false;
				}
			}
		}
		//--------check validate value input----------
		if (!Validate.validateEmail(sEmail)) {
			err = "Email is not validate !";
			return false;
		} else {
			if (!Validate.validatePassword(sPassword)) {
				err = "Password is not validate !";
				return false;
			}
		}
		
		return true;
	}
	
	private boolean register(){

//		try {
//			Decrypter decrypter = new Decrypter();
//            HttpPost post = new HttpPost("http://ltv.com.vn/e4u/api/register");
//            json.put("email", decrypter.encrypt(sEmail));
//            json.put("password", decrypter.encrypt(sPassword));
//            json.put("fullname", sFullName);
//            StringEntity se = new StringEntity( json.toString());  
//            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
//            post.setEntity(se);
//            response = client.execute(post);
//
//            /*Checking response */
//            if(response!=null){
//                InputStream in = response.getEntity().getContent(); //Get the data in the entity
//            }
//
//        } catch(Exception e) {
//        	return false;
//        }
		Decrypter decrypter;
		try {
			decrypter = new Decrypter();
			
			UserDTO userDTO = new UserDTO();
			UserDAO userDAO =new UserDAO(RegisterActivity.this);
			userDTO.setUsrEml(decrypter.encrypt(sEmail));
			userDTO.setUsrPwd(decrypter.encrypt(sPassword));			
			userDTO.setUsrNm(sFullName);
			userDTO.setUsrId(sEmail);
			userDAO.insert(userDTO);
			return true;
		} catch (Exception e) {			
			return false;
		}
	}
}
